<template>
  <base-table-layout
    title="农户余额管理"
    :total="total"
    :current-page="searchForm.pageNum"
    :page-size="searchForm.pageSize"
    @update:currentPage="val => searchForm.pageNum = val"
    @update:pageSize="val => searchForm.pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <div class="search-form-row">
          <el-form-item label="农户姓名">
            <el-input
              v-model="searchForm.growerName"
              placeholder="农户姓名"
              style="width: 200px"
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input
              v-model="searchForm.idCard"
              placeholder="请输入身份证号"
              style="width: 250px"
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              v-model="searchForm.phone"
              placeholder="联系电话"
              style="width: 250px"
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </div>
        <div class="search-form-row">
          <el-form-item label="余额上限">
            <el-input-number
              v-model="searchForm.remainingAmountLess"
              placeholder="余额小于等于"
              :min="0"
              style="width: 250px"
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
          <el-form-item label="所属部门">
            <dept-tree-select
              v-model="searchForm.deptId"
              placeholder="选择部门"
              width="250px"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <div class="button-group">
              <el-button type="primary" icon="el-icon-search" @click="handleSearch" class="form-button">搜索</el-button>
              <el-button type="info" icon="el-icon-refresh" @click="resetSearch" class="form-button">重置</el-button>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <div class="operation-buttons">
        <el-button type="success" icon="el-icon-plus" @click="handleAddBalance" class="operation-button">新增余额</el-button>
        <el-upload
          ref="upload"
          action="#"
          :http-request="handleExcelUpload"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleExcelChange"
          accept=".xlsx,.xls"
          class="upload-button-container"
        >
          <el-button type="primary" icon="el-icon-upload2" class="operation-button">Excel导入</el-button>
        </el-upload>
        <el-button type="success" icon="el-icon-download" @click="downloadTemplate" class="operation-button">下载模板</el-button>
        <el-button type="primary" icon="el-icon-download" @click="exportExcel" class="operation-button">导出Excel</el-button>
      </div>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="balanceList"
        border
        style="width: 100%"
      >
        <el-table-column prop="growerName" label="农户姓名" min-width="100" />
        <el-table-column prop="phone" label="联系电话" min-width="120" />
        <el-table-column prop="idCard" label="身份证号" min-width="180" />
        <el-table-column label="所属区域" min-width="200">
          <template slot-scope="scope">
            {{ scope.row.tobaccoStationName }}/{{ scope.row.townName }}/{{ scope.row.villageGroupName }}
          </template>
        </el-table-column>
        <el-table-column label="余额信息" align="center">
          <el-table-column prop="totalAmount" label="总充值数量" width="120" align="right">
            <template slot-scope="scope">
              <span>{{ scope.row.totalAmount }}亩</span>
            </template>
          </el-table-column>
          <el-table-column prop="usedAmount" label="已使用数量" width="120" align="right">
            <template slot-scope="scope">
              <span>{{ scope.row.usedAmount }}亩</span>
            </template>
          </el-table-column>
          <el-table-column prop="remainingAmount" label="剩余数量" width="120" align="right">
            <template slot-scope="scope">
              <span>{{ scope.row.remainingAmount }}亩</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleOperation(scope.row, 1)" class="table-button">充值</el-button>
            <el-button 
              size="mini" 
              type="warning" 
              @click="handleOperation(scope.row, 2)"
              :disabled="scope.row.remainingAmount <= 0"
              class="table-button"
            >扣除</el-button>
            <el-button 
              size="mini" 
              type="success" 
              @click="handleOperation(scope.row, 3)"
              :disabled="scope.row.usedAmount <= 0"
              class="table-button"
            >退款</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 操作对话框 -->
      <el-dialog
        :title="getOperationTitle"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="农户" prop="growerId" v-if="isNewRecord">
            <el-input
              v-model="selectedGrowerName"
              placeholder="请选择农户"
              readonly
              style="width: 100%"
              @click.native="showGrowerSelectDialog"
            />
          </el-form-item>
          <el-form-item label="农户" v-else>
            <el-select
              v-model="form.growerId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入农户姓名搜索"
              :remote-method="remoteSearchGrower"
              :loading="growerLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in growerOptions"
                :key="item.growerId"
                :label="item.growerName"
                :value="item.growerId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作类型" prop="operationType" v-if="isNewRecord">
            <el-select v-model="form.operationType" placeholder="请选择操作类型" style="width: 100%">
              <el-option label="充值" :value="1" />
              <el-option label="扣除" :value="2" />
              <el-option label="退款" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="amount">
            <el-input-number 
              v-model="form.amount" 
              :min="1" 
              :max="maxAmount"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <div class="dialog-button-group">
            <el-button @click="dialogVisible = false" class="dialog-button">取 消</el-button>
            <el-button type="primary" @click="submitForm" class="dialog-button">确 定</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 农户选择组件 -->
      <grower-select
        :visible.sync="growerSelectVisible"
        @select="handleGrowerSelect"
      />

      <!-- 批量充值对话框 -->
      <el-dialog
        title="批量充值"
        :visible.sync="batchDialogVisible"
        width="800px"
        :close-on-click-modal="false"
      >
        <el-table
          :data="batchForm"
          border
          style="width: 100%"
        >
          <el-table-column label="农户">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.growerId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入农户姓名搜索"
                :remote-method="remoteSearchGrower"
                :loading="growerLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in growerOptions"
                  :key="item.growerId"
                  :label="item.growerName"
                  :value="item.growerId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              <el-input-number 
                v-model="scope.row.amount" 
                :min="1"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button 
                type="text" 
                icon="el-icon-delete" 
                @click="removeBatchRow(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-button type="primary" icon="el-icon-plus" @click="addBatchRow" class="dialog-button">添加一行</el-button>
        </div>
        <div slot="footer" class="dialog-footer">
          <div class="dialog-button-group">
            <el-button @click="batchDialogVisible = false" class="dialog-button">取 消</el-button>
            <el-button type="primary" @click="submitBatchForm" class="dialog-button">确 定</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 导入进度对话框 -->
      <import-progress-dialog
        ref="progressDialog"
        :visible.sync="progressVisible"
        :total="importTotal"
        :current="importCurrent"
        :success-list="successList"
        :error-list="errorList"
      />
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import ImportProgressDialog from '@/components/ImportProgressDialog.vue'
import * as XLSX from 'xlsx'
import BaseTableLayout from '@/components/BaseTableLayout.vue'
import DeptTreeSelect from '@/components/DeptTreeSelect.vue'
import GrowerSelect from '@/components/GrowerSelect.vue'

export default {
  name: 'GrowerBalance',
  components: {
    ImportProgressDialog,
    BaseTableLayout,
    DeptTreeSelect,
    GrowerSelect
  },
  data() {
    return {
      loading: false,
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        growerName: '',
        idCard: '',
        phone: '',
        deptId: undefined,
        remainingAmountLess: undefined
      },
      balanceList: [],
      total: 0,
      dialogVisible: false,
      batchDialogVisible: false,
      form: {
        growerId: undefined,
        amount: 1,
        operationType: 1
      },
      batchForm: [
        {
          growerId: undefined,
          amount: 1,
          operationType: 1
        }
      ],
      rules: {
        growerId: [
          { required: true, message: '请选择农户', trigger: 'change' }
        ],
        operationType: [
          { required: true, message: '请选择操作类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      growerSelectVisible: false,
      selectedGrowerName: '',
      growerLoading: false,
      growerOptions: [],
      currentGrower: null,
      progressVisible: false,
      importTotal: 0,
      importCurrent: 0,
      successList: [],
      errorList: [],
      isNewRecord: false
    }
  },
  computed: {
    getOperationTitle() {
      const titles = {
        1: '充值',
        2: '扣除',
        3: '退款'
      }
      return titles[this.form.operationType] || '操作'
    },
    maxAmount() {
      if (this.form.operationType === 2) {
        return this.currentGrower ? this.currentGrower.remainingAmount : 999999
      } else if (this.form.operationType === 3) {
        return this.currentGrower ? this.currentGrower.usedAmount : 999999
      }
      return 999999
    }
  },
  created() {
    this.fetchBalanceList()
  },
  methods: {
    // 获取余额列表
    async fetchBalanceList() {
      try {
        this.loading = true
        const params = {
          pageNum: this.searchForm.pageNum,
          pageSize: this.searchForm.pageSize,
          growerName: this.searchForm.growerName || undefined,
          idCard: this.searchForm.idCard || undefined,
          phone: this.searchForm.phone || undefined,
          deptId: this.searchForm.deptId,
          remainingAmountLess: this.searchForm.remainingAmountLess
        }
        const response = await request.get('/grower/balance/page', { params })
        if (response) {
          this.balanceList = response.records || []
          this.total = response.total || 0
          this.searchForm.pageSize = response.size || 10
          this.searchForm.pageNum = response.current || 1
        }
      } catch (error) {
        console.error('获取余额列表失败:', error)
        this.$message.error('获取余额列表失败')
      } finally {
        this.loading = false
      }
    },

    // 批量查询余额信息
    async batchQueryBalance(growerIds) {
      try {
        const response = await request.post('/grower/balance/batch-query', growerIds)
        return response
      } catch (error) {
        console.error('批量查询余额失败:', error)
        this.$message.error('批量查询余额失败')
        return []
      }
    },

    handleSearch: _.debounce(function() {
      this.searchForm.pageNum = 1
      this.fetchBalanceList()
    }, 300),

    resetSearch() {
      this.searchForm = {
        pageNum: 1,
        pageSize: 10,
        growerName: '',
        idCard: '',
        phone: '',
        deptId: undefined,
        remainingAmountLess: undefined
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.fetchBalanceList()
    },

    handleCurrentChange(val) {
      this.searchForm.pageNum = val
      this.fetchBalanceList()
    },

    // 远程搜索农户
    async remoteSearchGrower(query) {
      if (query) {
        this.growerLoading = true
        try {
          const response = await request.get('/growers/search', {
            params: { keyword: query }
          })
          this.growerOptions = response.data
        } catch (error) {
          console.error('搜索农户失败:', error)
        } finally {
          this.growerLoading = false
        }
      } else {
        this.growerOptions = []
      }
    },

    // 显示农户选择对话框
    showGrowerSelectDialog() {
      this.growerSelectVisible = true
    },

    // 处理农户选择
    handleGrowerSelect(grower) {
      this.form.growerId = grower.growerId
      this.selectedGrowerName = `${grower.growerName}(${grower.deptName})`
    },

    // 处理新增余额
    handleAddBalance() {
      this.isNewRecord = true
      this.form = {
        growerId: undefined,
        amount: 1,
        operationType: 1
      }
      this.selectedGrowerName = ''
      this.dialogVisible = true
    },

    // 处理单个操作
    async handleOperation(row, type) {
      this.isNewRecord = false
      this.currentGrower = row
      this.form = {
        growerId: row.growerId,
        amount: 1,
        operationType: type
      }
      this.dialogVisible = true
    },

    // 处理批量充值
    handleBatchAdd() {
      this.batchForm = [{
        growerId: undefined,
        amount: 1,
        operationType: 1
      }]
      this.batchDialogVisible = true
    },

    // 添加批量行
    addBatchRow() {
      this.batchForm.push({
        growerId: undefined,
        amount: 1,
        operationType: 1
      })
    },

    // 移除批量行
    removeBatchRow(index) {
      this.batchForm.splice(index, 1)
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.form.validate()
        await request.post('/grower/balance/change', this.form)
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.fetchBalanceList()
      } catch (error) {
        console.error('操作失败:', error)
        this.$message.error(error.response?.data?.msg || '操作失败')
      }
    },

    // 提交批量表单
    async submitBatchForm() {
      try {
        // 验证数据
        const invalidData = this.batchForm.some(item => !item.growerId || !item.amount)
        if (invalidData) {
          this.$message.warning('请填写完整的农户和数量信息')
          return
        }

        await request.post('/grower/balance/batch-change', this.batchForm)
        this.$message.success('批量操作成功')
        this.batchDialogVisible = false
        this.fetchBalanceList()
      } catch (error) {
        console.error('批量操作失败:', error)
        this.$message.error(error.response?.data?.msg || '批量操作失败')
      }
    },

    // 处理Excel文件变化
    async handleExcelChange(file) {
      if (!file) return
      
      try {
        if (!XLSX) {
          throw new Error('XLSX库未正确加载')
        }

        const reader = new FileReader()
        reader.onload = async (e) => {
          try {
            if (!e.target || !e.target.result) {
              throw new Error('文件读取失败')
            }

            // 使用 Uint8Array 处理二进制数据
            const data = new Uint8Array(e.target.result)
            const workbook = XLSX.read(data, { type: 'array' })
            
            if (!workbook || !workbook.SheetNames || workbook.SheetNames.length === 0) {
              throw new Error('无效的Excel文件')
            }

            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]
            
            if (!worksheet) {
              throw new Error('工作表为空')
            }

            // 将工作表转换为JSON数据
            const excelData = XLSX.utils.sheet_to_json(worksheet)
            if (!excelData || excelData.length === 0) {
              throw new Error('Excel文件内容为空')
            }

            // 初始化导入进度
            this.importTotal = excelData.length
            this.importCurrent = 0
            this.successList = []
            this.errorList = []
            this.progressVisible = true

            // 处理每一行数据
            for (const row of excelData) {
              try {
                // 检查必要字段
                if (!row['身份证号'] || !row['充值面积']) {
                  throw new Error('缺少必要字段：身份证号或充值面积')
                }

                // 通过身份证号查询农户信息
                const growerResponse = await request.get('/growers/by-idcard', {
                  params: { idCard: row['身份证号'].toString().trim() }
                })

                if (!growerResponse || !growerResponse.growerId) {
                  throw new Error('未找到对应农户信息')
                }

                // 构建充值数据
                const rechargeData = {
                  growerId: growerResponse.growerId,
                  amount: Number(row['充值面积']),
                  operationType: 1 // 充值操作
                }

                // 执行充值操作
                await request.post('/grower/balance/change', rechargeData)

                // 添加到成功列表
                this.successList.push({
                  growerName: row['农户姓名'] || growerResponse.growerName,
                  idCard: row['身份证号'],
                  amount: row['充值面积']
                })
              } catch (error) {
                // 添加到失败列表
                this.errorList.push({
                  idCard: row['身份证号'],
                  reason: error.message || '处理失败'
                })
              }

              // 更新进度
              this.importCurrent++
            }

            // 完成导入
            this.$message.success(`导入完成：成功${this.successList.length}条，失败${this.errorList.length}条`)
          } catch (error) {
            console.error('Excel解析失败:', error)
            this.$message.error('Excel文件解析失败: ' + error.message)
          }
        }

        reader.readAsArrayBuffer(file.raw)
      } catch (error) {
        console.error('处理Excel文件失败:', error)
        this.$message.error('处理Excel文件失败')
      }
    },

    // 下载模板
    downloadTemplate() {
      try {
        // 模板数据
        const templateData = [
          {
            '农户姓名': '李廷琼',
            '身份证号': '533523197412345678',
            '充值面积': 12
          },
          {
            '农户姓名': '李绍华',
            '身份证号': '533523197312345678',
            '充值面积': 12
          }
        ]

        // 设置列的顺序
        const header = ['农户姓名', '身份证号', '充值面积']
        
        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(templateData, {
          header: header
        })
        
        // 设置列宽
        const colWidth = [
          { wch: 15 }, // 农户姓名
          { wch: 20 }, // 身份证号
          { wch: 10 }  // 充值面积
        ]
        worksheet['!cols'] = colWidth
        
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, '农户余额充值')
        XLSX.writeFile(workbook, '农户余额充值导入模板.xlsx')
      } catch (error) {
        console.error('下载模板失败:', error)
        this.$message.error('下载模板失败')
      }
    },

    // 处理Excel上传
    handleExcelUpload(event) {
      const file = event.file
      this.handleExcelChange({ raw: file })
    },

    // 导出Excel
    async exportExcel() {
      try {
        this.loading = true
        // 使用较大的pageSize以获取更多数据
        const exportParams = {
          pageNum: 1,
          pageSize: 10000, // 使用大的分页大小
          growerName: this.searchForm.growerName || undefined,
          idCard: this.searchForm.idCard || undefined,
          phone: this.searchForm.phone || undefined,
          deptId: this.searchForm.deptId,
          remainingAmountLess: this.searchForm.remainingAmountLess
        }
        
        // 获取数据
        const response = await request.get('/grower/balance/page', { params: exportParams })
        if (!response || !response.records) {
          this.$message.warning('没有数据可导出')
          this.loading = false
          return
        }
        
        const exportData = response.records
        if (exportData.length === 0) {
          this.$message.warning('没有数据可导出')
          this.loading = false
          return
        }
        
        // 准备导出数据
        const excelData = exportData.map(item => {
          return {
            '农户姓名': item.growerName,
            '身份证号': item.idCard,
            '联系电话': item.phone,
            '所属区域': `${item.tobaccoStationName || ''}/${item.townName || ''}/${item.villageGroupName || ''}`,
            '总充值数量(亩)': item.totalAmount,
            '已使用数量(亩)': item.usedAmount,
            '剩余数量(亩)': item.remainingAmount
          }
        })
        
        // 设置列的顺序
        const header = ['农户姓名', '身份证号', '联系电话', '所属区域', '总充值数量(亩)', '已使用数量(亩)', '剩余数量(亩)']
        
        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(excelData, {
          header: header
        })
        
        // 设置列宽
        const colWidth = [
          { wch: 15 }, // 农户姓名
          { wch: 20 }, // 身份证号
          { wch: 15 }, // 联系电话
          { wch: 40 }, // 所属区域
          { wch: 15 }, // 总充值数量
          { wch: 15 }, // 已使用数量
          { wch: 15 }  // 剩余数量
        ]
        worksheet['!cols'] = colWidth
        
        // 创建工作簿并添加工作表
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, '农户余额')
        
        // 获取当前时间作为文件名的一部分
        const now = new Date()
        const dateString = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`
        const fileName = `农户余额_${dateString}.xlsx`
        
        // 导出工作簿
        XLSX.writeFile(workbook, fileName)
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出Excel失败:', error)
        this.$message.error('导出Excel失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
  
  .dialog-button-group {
    display: inline-flex;
    gap: 10px;
  }
}

.search-form {
  .el-form-item {
    margin-bottom: 10px;
    margin-right: 10px;
  }
  
  .search-form-row {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    margin-bottom: 5px;
  }
  
  .form-button {
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .button-group {
    display: flex;
    gap: 10px;
  }
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin: 8px 0;
}

:deep(.el-upload) {
  display: inline-block;
}

:deep(.el-dialog__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px;
  border-top: 1px solid #dcdfe6;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.operation-button {
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.table-button {
  height: 28px;
  padding: 5px 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.dialog-button {
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-button-container {
  height: 32px;
  margin-right: 0;

  :deep(.el-button) {
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>